package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
@Slf4j
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1。先通过身份证和状态判断老人是否已经入住
        Elder elder1 = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        if (elder1 != null) {
            //已经入住
            return;
        }
        //更新床位的状态
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //新增或更新老人表
        Elder elder = insertOrUpdate(checkInApplyDto, bed);

        //新增签约合同表
        insertContract(checkInApplyDto, elder);

        //新增入住表
        CheckIn checkIn = saveCheckIn(checkInApplyDto, elder);
        //新增入住配置表
        insertCheckInConfig(checkIn.getId(), checkInApplyDto);

    }

    /**
     * 根据入住id查询入住详情
     *
     * @param id
     * @return CheckInDetailVo
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        Long elderId = checkIn.getElderId();
        //查询老人信息
        Elder elder = elderMapper.selectById(elderId);
        //封装老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        Integer birthYear = Integer.valueOf(elder.getIdCardNo().substring(6, 10));
        Integer now = Integer.valueOf(LocalDate.now().toString().substring(0, 4));
        checkInElderVo.setAge(now - birthYear);
        log.warn("checkInElderVo:{}", checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //查询合同
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elderId));
        log.warn("contract:{}", contract);
        checkInDetailVo.setContract(contract);
        //查询入住配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInConfig newCheckInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        BeanUtils.copyProperties(newCheckInConfig, checkInConfigVo);


        log.warn(" checkInCinfigVo:{}", checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //转换家属列表
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        log.warn("elderFamilyVoList:{}", elderFamilyVoList);
        return checkInDetailVo;

    }

    /**
     * 新增入住配置表
     *
     * @param id
     * @param checkInApplyDto
     */

    private void insertCheckInConfig(Long id, CheckInApplyDto checkInApplyDto) {

        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住表
     *
     * @param checkInApplyDto
     * @param elder
     * @return
     */

    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        checkIn.setStartDate(startDate);
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        boolean flag = startDate.isBefore(LocalDateTime.now());
        checkIn.setStatus(flag ? 0 : 1);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约合同表
     *
     * @param checkInApplyDto
     */
    private void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        String contractNumber = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);
        contract.setElderName(elder.getName());
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        boolean flag = startDate.isBefore(LocalDateTime.now());
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(flag ? 1 : 0);
        contractMapper.insert(contract);
    }

    /**
     * 新增签约合同表
     *
     * @param checkInApplyDto
     * @param bed
     * @return
     */
    private Elder insertOrUpdate(CheckInApplyDto checkInApplyDto, Bed bed) {
        Elder newElder = new Elder();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), newElder);
        newElder.setStatus(1);
        newElder.setBedNumber(bed.getBedNumber());
        newElder.setBedId(bed.getId());
        //判断是新增还是更新
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .ne(Elder::getStatus, 1));

        if (oldElder == null) {
            //新增
            elderMapper.insert(newElder);
        } else {
            //更新
            elderMapper.updateById(newElder);
        }
        return newElder;
    }
}
